<!--   
Persistent Digital Archives and Library System (PeDALS) 
(c) 2008 - All Rights Reserved
//-->
<?php
//form validation 
if (isset($_POST['CreateProv'])){	
	if (empty($_POST['NameAuthorityForm'])){		
		$m1 = "Please enter an Authority Name";
		$submitForm = 1;
		}
		
/*if (isset($_POST['info_input']) && isset($_POST['data_input'])){
	$arrayVar = array($_POST["info_input"],$_POST["data_input"]);
	foreach($arrayVar as $info => $data) {            
		if (($info == "") or ($data == "")) {
			$m3 = "Both variant qualifier and name must be entered.<br/>";
			$submitForm = 1;
		}
	}
}*/					
				
	if (!isset($submitForm)){		
		include 'includes/config.php'; 
		/*Get all the field values from user input*/
			$provName = $_POST["NameAuthorityForm"];
			$provAdminHist = $_POST["AdministrativeHistory"];
			$provGenNote = $_POST["GeneralNote"];
			$provId = 0;

			//check if is submit extra value
			if (isset($_POST['info_input']) && isset($_POST['data_input'])){
				$arrayVar = array($_POST["info_input"],$_POST["data_input"]);
				}		
		
			/*check if this is a new provenance or if it as already been created*/	
				$provnameparam = array(ltrim(rtrim($provName)));	
				$tsqlProvCheck = "SELECT ProvenanceName FROM Provenance WHERE ProvenanceName = ?";
			
				$getData = sqlsrv_prepare( $conn, $tsqlProvCheck, $provnameparam);
				if( $getData === false ) {
					 echo "Error in preparing statement.<br/><br/><br/><br/>\n";
					 die;
				}

				if( sqlsrv_execute( $getData))
				{   
				/*echo "Statement executed.\n";*/
				}
				else
				{
					 echo "Error in executing statement.<br/><br/><br/><br/>\n";
					 die;
				}
				$rowCount = 0;
				while (sqlsrv_fetch( $getData ))
				{	
					$rowCount++;
				}
				
			if ($rowCount > 0) {
				echo "This provenance was already created.";
				die;
			};

		
		/*Call the stored procedure that inserts data into the Provenance table*/
			$tsql_callSP = "{call PAC_CreateProvenance( ?, ?, ?, ?)}";  
			$params = array(   
							 array($provName, SQLSRV_PARAM_IN),  
							 array($provAdminHist, SQLSRV_PARAM_IN),
							 array($provGenNote, SQLSRV_PARAM_IN),
							 array($provId, SQLSRV_PARAM_OUT)   
						   );  
			$stmt = sqlsrv_query( $conn, $tsql_callSP, $params);  
			
			//check if execute sql if NOT error
			if (!$stmt){
				$SQLmessageError = "Provenance was not added to database due to an error.";
				$SQLErrorDB = print_r(sqlsrv_errors(),true);
				$SQLErrorDBcheck = 1;
				sqlsrv_close($conn);
				exit;
				}		
		
		/*For each row of variant names, call the stored procedure that inserts data into the ProvenanceVariant table*/
		$tsql_callSP = "{call PAC_CreateProvenanceVariant( ?, ?, ?)}"; 
				
				
				//add values if user put some data and the same key values
				if (!empty($arrayVar)){				
				$myArrayPosition =  0;
					foreach($arrayVar[0] as $key) {
					$value = $arrayVar[1][$myArrayPosition];
					$myArrayPosition ++;
								$params = array(   
									 array($provId, SQLSRV_PARAM_IN),
									 array($key, SQLSRV_PARAM_IN),  
									 array($value, SQLSRV_PARAM_IN) 
								   ); 
								   $stmt = sqlsrv_query( $conn, $tsql_callSP, $params);	
								   //validate SQL execute for each Variant catch error
								   if (!$stmt){
										$SQLmessageError = "One or more variant names were not added due to an error.<br.>View provenance detail to find out what hasn't been created.";
										$SQLErrorDB = print_r(sqlsrv_errors(),true);
										$SQLErrorDBcheck = 1;
										sqlsrv_close($conn);
										break;
										}	
					}
				}
				
			if (!isset($SQLErrorDBcheck)){
				include("includes/addProvSuccess.php");
				sqlsrv_close( $conn);
				exit;
			}			
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="description" content="Persistent Digital Archives and Library System" />
<title>PeDALS Web Administration</title>
<link rel="shortcut icon" href="images/favicon.ico" />
<link href="includes/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="includes/showdesc.js"></script>
</head>
<body>
<?php include 'includes\header.php'; ?>

<script language="javascript">
/*April 1 2009
Function add Element create on-the-fly new DIV switch holds everything that we want to put on our website
Function remove element delete one element from our div
*/
var nextNumber = 0;

function addElement() {
	if (document.getElementById("NameAuthorityForm").value == ""){
		alert("Please enter an Authority Name before adding a Variant Name");
		}
	else{	
  nextNumber += 1;  
  var newDiv = document.createElement('div');
  var divId = 'input'+nextNumber+'Div';
  newDiv.setAttribute('id',divId);
  newDiv.innerHTML = '<tr><td style=\"padding: 5px;\"><input type=\"text\" name=\"info_input[]\" maxlength=\"50\" size=\"25\"></td><td style=\"padding: 5px;\"><input type=\"text\" name=\"data_input[]\" maxlength=\"100\" size=\"45\"></td><td><a href=\"javascript:;\" onclick=\"removeElement(\''+divId+'\');\" style=\"text-decoration: none;\">&nbsp;<img border=\"0\" src=\"images/delete.png\"/></a></td></tr>'; 
  document.getElementById('contentDiv').appendChild(newDiv);
	}
}
function removeElement(divNum) {
    document.getElementById('contentDiv').removeChild(document.getElementById(divNum));
}
</script>
<div id="breadcrumb-container">
  <div id="breadcrumb"><a href="index.php" title="Home page">Home</a> / <a href="provSummary.php" title="Provenances">Provenances</a> / Add Provenance</div>
  <div id="breadcrumb-side"><form name="search" action="search.php"><input type="text" name="q" width="50"/><input type="submit" value="Go" /></form><a href="advSearch.php" title="Advanced Search" alt="Advanced Search">Advanced Search</a>
  </div>
  <div class="clear"></div>
</div>
<!-- 
  CONTENT
  -->
<div id="content-container">

  <!-- 
	SIDE COLUMN
	-->
  <div id="content-side">
    <ul class="link-list-vertical">
      <li><a href="provSummary.php" title="View a list of all Provenances in PeDALS.">List Provenances</a></li>
      <li><a href="provNew.php" title="Add an Provenance to PeDALS.">Add Provenance</a></li>
    </ul>
  </div>
  <!-- 
	MAIN COLUMN
	-->
  <div id="content"><a name="maincontent" id="maincontent"></a>
    <h1>Add Provenance</h1>
    
<?php 
//error message box 
if(isset($SQLErrorDB) && isset($SQLmessageError)){
$errorDiv = <<<__HTML_END
    <div style="padding-right:20px; font-size:16px; color:#F00;">$SQLmessageError
    <div style="cursor:pointer; color:#900; font-size: 12px;" onclick="if(document.getElementById('sqlServerErrorMessage').style.display == 'none')document.getElementById('sqlServerErrorMessage').style.display = ''; else document.getElementById('sqlServerErrorMessage').style.display = 'none';">Show error details</div>    
    <div id="sqlServerErrorMessage" style="background-color:#FFFFFF; color:#000; font-family:'Courier New', Courier, monospace; font-size:12px; border:1px solid #F00; width:100%; display:none; padding:7px;">$SQLErrorDB</div>    
    </div>
__HTML_END;
echo $errorDiv;
}
?>
<?php include 'coredata.php'; ?> 
<form action="" method="POST"> 
<!--validation message-->
<p><strong>Authority Name (mandatory)</strong> (<a onclick="showhide('div101');" class="desclink">101</a>)<span style=" padding-left:20px; position:absolute; float:right; color:red;">
	<?php //validation message
		if (isset($m1)){echo $m1;}
    ?>
</span><br/>
<!--/ validation message-->
<input type="text" id="NameAuthorityForm" name="NameAuthorityForm" maxlength="100" size="86" value="<?php if (isset($_REQUEST['NameAuthorityForm'])){echo $_REQUEST['NameAuthorityForm'];}?>"></p>
<!--validation message-->
<strong>Administrative History</strong> (<a onclick="showhide('div103');" class="desclink">103</a>)<span style=" padding-left:20px; position:absolute; float:right; color:red;">
</span>
<!--/ validation message-->
<p><textarea name="AdministrativeHistory" rows="15" cols="65"><?php if (isset($_REQUEST['AdministrativeHistory'])){echo $_REQUEST['AdministrativeHistory'];}?></textarea></p>
<strong>General Note</strong> (<a onclick="showhide('div105');" class="desclink">105</a>)<span style=" padding-left:20px; position:absolute; float:right; font-style:bold;">
</span>
<p><textarea name="GeneralNote" rows="10" cols="65"><?php if (isset($_REQUEST['GeneralNote'])){echo $_REQUEST['GeneralNote'];}?></textarea></p>
<p><strong>Variant Forms of Name</strong> (<a onclick="showhide('div102');" class="desclink">102</a>)</p> <span style=" padding-left:20px; position:absolute; float:right; color:red;">
	<?php 
		if (isset($m3)){echo $m3;}
    ?></span>
        <table class="table" border="1" cellspacing="0" summary="Table listing">
      <thead>
        <tr>
          <th scope="col" width="100">Type of Variant</th>
          <th scope="col" width="250">Variant for Name</th>
        </tr>
      </thead>
      <tbody>
      		<tr><td colspan="2"><a href="javascript: addElement();" style="text-decoration: none; vertical-align: text-middle;"><img border="0" src="images/add.png"/>Add Variant Name</a>
			<div id="contentDiv"></div></td></tr>
	</tbody>
	</table>
<br/>
	  <input type="submit" value="submit" name="CreateProv" title="submit"><br />
      <input type="hidden" name="_submit_check" value="1"/> 
</form>
<!--Perform the following if user clicks on the submit button-->
<?php
if (array_key_exists('_submit_check', $_POST)) {
}
?>

<?php include 'includes\footer.php'; ?>
  </div>
</div>
</body>
</html>